package com.zyd.blog.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyd.blog.business.entity.ArticleFavor;
import com.zyd.blog.business.service.BizArticleFavorService;
import com.zyd.blog.business.vo.ArticleFavorConditionVO;
import com.zyd.blog.persistence.beans.BizArticleFavor;
import com.zyd.blog.persistence.beans.BizCaredUser;
import com.zyd.blog.persistence.mapper.BizArticleFavorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * 文章浏览记录
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @website https://www.zhyd.me
 * @date 2018/4/16 16:26
 * @since 1.0
 */
@Service
public class BizArticleFavorServiceImpl implements BizArticleFavorService {

    @Autowired
    private BizArticleFavorMapper bizArticleFavorMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ArticleFavor insert(ArticleFavor entity) {
        Assert.notNull(entity, "ArticleFavor不可为空！");
        entity.setUpdateTime(new Date());
        entity.setCreateTime(new Date());
        bizArticleFavorMapper.insertSelective(entity.getBizArticleFavor());
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ArticleFavor delete(ArticleFavor entity) {
        Assert.notNull(entity, "ArticleFavor不可为空！");
        entity.setUpdateTime(new Date());
        entity.setCreateTime(new Date());
        Example example = new Example(BizArticleFavor.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("articleId", entity.getArticleId());
        criteria.andEqualTo("userId", entity.getUserId());
        bizArticleFavorMapper.deleteByExample(example);
        return entity;
    }

    /**
     * 分页查询
     *
     * @param vo
     * @return
     */
    @Override
    public PageInfo<ArticleFavor> findPageBreakByCondition(ArticleFavorConditionVO vo) {
        PageHelper.startPage(vo.getPageNumber(), vo.getPageSize());
        List<BizArticleFavor> list = bizArticleFavorMapper.findPageBreakByCondition(vo);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        PageInfo bean = new PageInfo<BizArticleFavor>(list);
        return bean;
    }

    @Override
    public Long findFavorId(ArticleFavorConditionVO vo) {
        BizArticleFavor bizArticleFavor = bizArticleFavorMapper.findFavorId(vo);
        if(bizArticleFavor != null) {
            return bizArticleFavorMapper.findFavorId(vo).getId();
        }
        return null;
    }


}
